<template>
  <div class="home-address-edit-wrap" >
        <van-nav-bar
		  :title="id ? '编辑地址' : '添加地址'"
		  left-arrow
		  fixed
		  @click-left="onClickLeft"
		/>

        <div class="input-ul" >
            <van-field v-model="name" required label="联系人："  placeholder="请填写姓名" />
            <van-field
                v-model="phone"
                required
                type="tel"
                label="手机号："
                placeholder="请输入手机号"
            />
            <van-field
                v-model="address"
                required
                readonly
                label-width="76px"
                label="收货地址："
                :right-icon="goodCeilArrow"
                placeholder="请选择收货地址"
                @click="showPopup = true"
            />
            <van-field
                v-model="details"
                required
                label-width="76px"
                label="详细地址："
                placeholder="请填写详细地址"
            />
            <div></div>
        </div>

        <div 
        @click="default_flag = !default_flag"
        class="default-tag" >
            <img class="default-tag-icon" :src="!default_flag  ? defaultCircle : defaultTagIcon" alt="">
            <div  class="default-tag-name" >设为默认地址</div>
        </div>

        <div class="save-btn active-btn" @click="handleToSave" >保存</div>


        <!-- 地址 -->
        <van-popup v-model="showPopup" position="bottom">

            <van-cascader
            v-model="cascaderValue"
            title="请选择地址"
            :options="options"
            @close="showPopup = false"
            @change="onChange"
            @finish="onFinish"
            />


        </van-popup>

  </div>
</template>

<script>
import { goodCeilArrow, defaultTagIcon, defaultCircle } from '@/tool/static-img';
import { REGION_LIST, ADDRESS_CREATE, ADDRESS_DETAIL, ADDRESS_UPDATE } from '@/api/home';
import { checkPhone } from '@/tool/methods';
export default {
    data() {
        return {
            goodCeilArrow, defaultTagIcon, defaultCircle,
            id: '',
            name: '',
            phone: '',
            address: '',
            details: '',

            
            // 地址
            selectAreaList: [], // 已选中地区
            default_flag: false,
            showPopup: false,
            cascaderValue: '',
            options: [],
            tabIndex: 0,

            //操作
            loadBtn: false
        }
    },
    created() {
        const id = this.$route.query.id;
        if(id) {
            this.id = id;
            this.getAddressData(id);

            document.title = '编辑地址';
        }else {
            // 初始化时加载省级数据
            this.fetchRegions(1, 0);
            document.title = '添加地址';
        }
    },
    methods: {
        onClickLeft() {
            this.$router.back()
        },
        // 确认选择的回调
        onConfirm() {
            this.showPopup = false;
            console.log('选择的结果:', this.selectedValues);
        },
        // 取消选择的回调
        onCancel() {
            this.showPopup = false;
        },
        // 地址详情
        async getAddressData(id) {
            const res = await this.$http.get(ADDRESS_DETAIL + id)

                    const {
                        data
                    } = res;
                    if(data && data.address) {
                        this.name = data.address.name;
                        this.phone = data.address.phone;
                        this.cascaderValue = data.address.town_code;
                        this.details = data.address.details;
                        this.default_flag = data.address.default_flag === 1 ? true : false;

                        this.address = data.address.province_name + '/' + data.address.city_name + '/' + data.address.county_name ;
                        if(data.address.town_name) {
                            this.address = this.address + '/' + data.address.town_name;
                        }

                        // 加载地址选项
                        await this.fetchRegions(1, 0);
                        await this.fetchRegions(data.address.province_code, 1);
                        await this.fetchRegions(data.address.city_code, 2);
                        await this.fetchRegions(data.address.county_code, 3);
                    }
                

        },
        // 选择器变化时的回调
        onChange(res) {
            this.tabIndex = res.tabIndex;
            if(this.tabIndex === 3) {
                return;
            }
            console.log(res, 'jj')
            //点击加载下一级回调
            this.getSpaceListAgain(res.selectedOptions, res.value);
        },
        getSpaceListAgain(selectedOptions, value) {
            this.$http.get(REGION_LIST, {
                params: {
                    code: value
                }
            })
            .then(res => {
                let {
                    data
                } = res;
				
				
				if(this.tabIndex == 2 && !data.length) {
					data = [{
						code: 0,
						name: '暂不选择',
						parent_code: value
					}]
				}

                if(data && data.length) {
                    this.setOptions(selectedOptions, data);
                }
            })
        },
        setOptions(selectedOptions, data) {
            let _options = this.options;
            selectedOptions.forEach((item, index) => {
                if (index) {
                    //不是第一个则取下一级children
                    _options = _options.children;
                }
                _options = _options[_options.findIndex((_item) => _item.value === item.value)];
            });
            //找到最后一级
            _options.children = data.map((item) => {
                return {
                    text: item.name,
                    value: item.code,
                    children: this.tabIndex == 2 ? null : [],
                };
            });
        },
        onFinish({ selectedOptions }) {

            this.showPopup = false;

            this.selectAreaList = selectedOptions;

            selectedOptions = selectedOptions.filter(item => {

                return item.value !== 0;
            })

            console.log(selectedOptions, 'll')

            this.address = selectedOptions.map((option) => option.text).join('/');
        },
        async fetchRegions(parentCode, level) {
            const res = await this.$http.get(REGION_LIST, {
                params: {
                    code: parentCode
                }
            })
                let {
                    data
                } = res;
				
				if(level == 3 && !data.length) {
					data = [{
						name: '暂无选择',
						code: 0,
						parent_code: parentCode
					}]
				}

                // 省级
                if(level === 0) {
                    data.forEach(item => {
                        this.options.push({
                            text: item.name,
                            value: item.code,
                            children: []
                        });
                    })
                } else if(level === 1) {
                    // 市级数据
                    const province = this.options.find(item => item.value === parentCode);
                    if (province) {
                        province.children = data.map(item => ({
                            text: item.name,
                            value: item.code,
                            children: []
                        }));
                    }
                } else if(level === 2) {
                    // 区/县级数据
                    this.options.forEach(province => {
                        const city = province.children.find(item => item.value === parentCode);
                        if (city) {
                            city.children = data.map(item => ({
                                text: item.name,
                                value: item.code,
                                children: []
                            }));
                        }
                    });
                }else if(level === 3) {
                    // 街道数据
                    this.options.forEach(province => {
                        province.children.forEach(city => {
                            const county = city.children.find(item => item.value === parentCode);
                            if (county) {
                                county.children = data.map(item => ({
                                    text: item.name,
                                    value: item.code
                                }));
                            }
                        });
                    });
                }
        },
        handleToSave() {
            if(!this.name.trim()) {
                this.$toast('请输入联系人')
                return
            }
            if(!this.phone) {
                this.$toast('请输入手机号')
                return
            }
            if(!checkPhone(this.phone)) {
                this.$toast('手机号格式错误')
                return 
            }
            if(!this.selectAreaList.length) {
                this.$toast('请选择收货地址')
                return 
            }
            if(!this.details.trim()) {
                this.$toast('请填写详细地址')
                return
            }

            // 阻断校验
            if (this.loadBtn) {
                return;
            }
            // 锁住
            this.loadBtn = true;

            let params = {};
                params['name'] = this.name;
                params['phone'] = this.phone;
                params['province_code'] = this.selectAreaList[0].value;
                params['city_code'] = this.selectAreaList[1].value;
                params['county_code'] = this.selectAreaList[2].value;
                params['town_code'] = this.selectAreaList[3].value;
                params['details'] = this.details;
                params['default_flag'] = this.default_flag ? 1 : 0;

                if(this.id) {
                    params['id'] = this.id;
                }

                this.$http.post(this.id ? ADDRESS_UPDATE : ADDRESS_CREATE, params)
                    .then(() => {
                        this.$toast.success(this.id ? '编辑成功' : '添加成功');
                        setTimeout(() => {
                          this.loadBtn = false;
                          // 去登录
                          this.$router.back();
                        }, 800)
                    })
                    .catch(() => {
                        this.loadBtn = false;
                    })

        }
    }
}

</script>
<style lang="scss" >
.home-address-edit-wrap{
    position: relative;
    min-height: 100vh;
    padding-top: 46px;
    background-color: #ffffff;
    box-sizing: border-box;
    .van-nav-bar .van-icon{
        color: #333333;
    }
    .van-nav-bar__arrow{
        font-size: 20px;
    }
    .van-hairline--bottom::after{
        display: none;
    }
    .van-cell{

        padding-left: 26px;
    }
    .van-cell::after{
        left: 0;
        right: 0;
    }
    .van-field{
        padding-top: 14px;
        padding-bottom: 14px;
    }
    .van-cell--required::before{
        left: 16px;
    }
    .van-field__label{
        width: 70px;
        margin-right: 2px;
        color: #333333;
    }

    .default-tag{
        display: flex;
        align-items: center;
        margin-top: 0.24rem;
        margin-left: 0.36rem;
        .default-tag-icon{
            width: 0.32rem;
            height: 0.32rem;
            margin-right: 0.16rem;
        }
        .default-tag-name{
            font-weight: 400;
            font-size: 0.28rem;
            color: #999999;
        }
    }

    .save-btn{
        display: flex;
        align-items: center;
        justify-content: center;
        width: 6.06rem;
        height: 0.88rem;
        margin: auto;
        margin-top: 1.24rem;
        font-weight: 500;
        font-size: 0.32rem;
        color: #ffffff;
        border-radius: 0.16rem;
        background: linear-gradient( 270deg, #FD6D17 0%, #FF5E40 100%);
    }
}
</style>